import { Component, Prefab, _decorator, Node, instantiate, director } from "cc";
import {
  ApiMsgEnum,
  IApiPlayerListRes,
  IMsgGameStart,
  IMsgRoom,
  IRoom,
} from "../Common";
import { PlayerManager } from "../UI/PlayerManager";
import DataManager from "../Global/DataManager";
import NetworkManager from "../Global/NetworkManager";
import { SceneEnum } from "../Enum";
import { deepClone } from "../Utils";

const { ccclass, property } = _decorator;
@ccclass("RoomManager")
export class RoomManager extends Component {
  @property(Node)
  playerContent: Node;

  @property(Prefab)
  playerPref: Prefab;

  protected onLoad(): void {
    director.preloadScene(SceneEnum.Battle);

    NetworkManager.Instance.listenMsg(
      ApiMsgEnum.MsgRoom,
      this.handleRoomMsg,
      this
    );

    NetworkManager.Instance.listenMsg(
      ApiMsgEnum.MsgGameStart,
      this.handleGameStart,
      this
    );
  }

  protected start(): void {
    // this.playerContent.removeAllChildren();
    this.renderPlayer({
      room: DataManager.Instance.roomInfo,
    });
  }

  protected onDestroy(): void {
    NetworkManager.Instance.unlistenMsg(
      ApiMsgEnum.MsgRoom,
      this.handleRoomMsg,
      this
    );

    NetworkManager.Instance.unlistenMsg(
      ApiMsgEnum.MsgGameStart,
      this.handleGameStart,
      this
    );
  }

  renderPlayer({ room: { players: list } }: IMsgRoom) {
    for (let child of this.playerContent.children) {
      child.active = false;
    }

    while (this.playerContent.children.length < list.length) {
      let newPlayer = instantiate(this.playerPref);
      newPlayer.addComponent(PlayerManager);

      newPlayer.setParent(this.playerContent);
    }

    for (let i = 0; i < list.length; i++) {
      let pm = this.playerContent.children[i].getComponent(PlayerManager);
      pm.init(list[i]);
    }
  }

  async handleLeaveRoom() {
    const { success, error, res } = await NetworkManager.Instance.callApi(
      ApiMsgEnum.ApiRoomLeave,
      {}
    );

    if (!success) {
      console.log(error);
      return;
    }

    DataManager.Instance.roomInfo = null;

    director.loadScene(SceneEnum.Hall);
  }

  async handleClickStart() {
    const { success, error, res } = await NetworkManager.Instance.callApi(
      ApiMsgEnum.ApiGameStart,
      {}
    );

    if (!success) {
      console.log(error);
      return;
    }
  }

  async handleGameStart(data: IMsgGameStart) {
    DataManager.Instance.state = data.state;
    DataManager.Instance.lastState = deepClone(data.state);
    director.loadScene(SceneEnum.Battle);
  }

  handleRoomMsg(room: IMsgRoom) {
    console.log("roomMsg", room);
    this.renderPlayer(room);
  }
}
